<template>
  <!-- 最大的容器 -->
  <div class="formDate">
    <!-- 容器的内容 -->
    <div class="formItem">

      <!-- 容器内顶部内容 -->
      <div class="content_top">
        <div class="Text_content">
          <h3>欢迎登录</h3>
          <p>游戏街区，更多好玩立即登录获取哦</p>
        </div>
      </div>

      <!-- 容器内替换内容 -->
      <div class="replace">

        <!-- 文字下方的小横线 -->
        <div class="active-bar" :style="{ transform: `translateX(${activeTab === 'sms' ? '0' : '100%'})` }"></div>
        <div class="text_message" @click="activeTab = 'sms'">
          短信登录
        </div>
        <div class="passwrd_message" @click="activeTab = 'password'">
          密码登录
        </div>
      </div>

      <!-- 容器内用户登录表单 -->
      <!-- 短信登录表单 -->
      <div v-if="activeTab === 'sms'" class="content_login">
        <form :model="Form" @submit.prevent="handleSmsLogin">
          <div class="form_phone">
            <el-input v-model="Form.phone" placeholder="请输入手机号">
              <template #prepend>
                <div class="area-code">+86</div>
              </template>
            </el-input>
          </div>
          <div class="form_code">
            <el-input v-model="Form.code" placeholder="请输入验证码">
              <template #append>
                <span class="get-code-text" @click="getSendCode" :class="{ 'disabled': isCounting }">
                  {{ countdown > 0 ? `${countdown}s后重新获取` : '获取验证码' }}
                </span>
              </template>
            </el-input>
          </div>
          <div class="btn">
            <el-button type="primary" :loading="loading" :disabled="loading" @click="handleSmsLogin">登录</el-button>
          </div>
        </form>
      </div>

      <!-- 密码登录表单 -->
      <div v-else class="content_login">
        <form :model="Form">
          <div class="form_username">
            <el-input v-model="Form.username" placeholder="请输入用户名" />
          </div>
          <div class="form_password">
            <el-input 
              v-model="Form.password" 
              type="password" 
              placeholder="请输入密码" 
              show-password 
              @keyup.enter="handleLogin" 
            />
          </div>
          <div class="btn">
            <el-button type="primary" :loading="loading" :disabled="loading" @click="handleLogin">登录</el-button>
          </div>
        </form>

        <!-- 忘记密码和立即找回 -->
        <div class="forget">
          <span>忘记密码？</span>
          <span>遇到问题</span>
        </div>
      </div>
    </div>
  </div>



</template>

<script setup>
import { ref, computed } from 'vue';
import service from '@/utils/request';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/user';

const Form = ref({
  username: '',
  password: '',
  phone: '',
  code: '',
})

const activeTab = ref('sms')

const loading = ref(false)

const emit = defineEmits(['success'])

const userStore = useUserStore();
const reg = /^1[3-9]\d{9}$/

// 获取验证码请求
const getSendCode = async () => {

  if (!Form.value.phone) {
    ElMessage.error('请输入手机号');
    return; // 添加return，避免继续执行
  }
  if (!reg.test(Form.value.phone)) {
    ElMessage.error('请输入正确的手机号');
    return; // 添加return，避免继续执行
  }

  try {
    // 启动倒计时
    startCountdown();
    // 发送请求获取验证码
    const res = await service.get('/user/getPhoneCode', {
      params: {
        phone: Form.value.phone
      }
    });

    // 处理响应
    if (res.code == 400) {
      ElMessage.error(res.message || '验证码发送失败');
      return;
    }

    // 提取验证码
    const verificationCode = res.data?.code || extractCodeFromMessage(res.message);
    if (!verificationCode) {
      throw new Error('验证码格式异常');
    }

    ElMessage.success(`验证码已发送,1分钟内有效`);
    console.log('测试用验证码:', verificationCode); // 仅开发环境保留

  } catch (error) {
    console.error('获取验证码失败:', error);
    ElMessage.error('验证码发送失败，请稍后重试');
  }
}

function extractCodeFromMessage(message) {
  const codeMatch = message.match(/\b\d{4,6}\b/);
  return codeMatch ? codeMatch[0] : null;
}

const handleLogin = async () => {
  if (Form.value.username == '') {
    ElMessage.error('请输入内容');
  } else {
    loading.value = true;
    setTimeout(async () => {
      try {
        const res = await service.post('/user/login', Form.value);
        if (res.code == 200) {
          ElMessage.success('登录成功');
          userStore.setUserInfo(res.data); // 存储用户信息
          Form.value = { username: '', password: '' };
          emit('success');
          console.log(res);
        } else {
          ElMessage.error(res.msg || '登录失败');
        }
      } finally {
        loading.value = false;
      }
    }, 1500);
  }
};

const handleSmsLogin = async () => {
  if (!Form.value.phone) {
    ElMessage.error('请输入手机号');
    return;
  }
  if (!Form.value.code) {
    ElMessage.error('请输入验证码');
    return;
  }

  loading.value = true;
  setTimeout(async () => {
    try {
      const res = await service.post('/user/sendCode', null, {
        params: {
          phone: Form.value.phone,
          code: Form.value.code,
        },
      });
      if (res.code === 400) {
        ElMessage.error(res.message || '登录失败');
        console.log(res);
      } else {
        ElMessage.success('登录成功');
        userStore.setUserInfo(res.data); // 存储用户信息
        emit('success');
        Form.value = { phone: '', code: '' };
      }
    } catch (error) {
      ElMessage.error('登录失败');
    } finally {
      loading.value = false;
    }
  }, 1000);
};
const countdown = ref(0)
const isCounting = computed(() => countdown.value > 0)

const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    if (countdown.value <= 0) {
      clearInterval(timer);
      return;
    }
    countdown.value--;
  }, 1000);
}
</script>



<style lang="scss" scoped>
// 顶部添加CSS变量
$form-bg: #fff;
$form-radius: 8px;
$form-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
$input-height: 40px;
$primary-color: #409eff;

.formDate {
  max-width: 400px;
  padding: 24px;
  background: $form-bg;
  border-radius: $form-radius;

  .formItem {
    width: 100%;

    .content_top {
      text-align: center;
      margin-bottom: 24px;

      h3 {
        color: $primary-color;
        margin-bottom: 8px;
      }

      p {
        color: #666;
      }
    }

    .replace {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      margin-bottom: 24px;
      border-bottom: 1px solid #e4e7ed;
      padding-bottom: 8px;

      .active-bar {
        position: absolute;
        bottom: -1px;
        left: 0;
        width: 50%;
        height: 2px;
        background: $primary-color;
        transition: transform 0.3s ease-in-out; // 可以调整0.3s来改变移动速度
      }

      .text_message,
      .passwrd_message {
        cursor: pointer;
        width: 50%;
        text-align: center;
        padding: 8px 0;
        color: #606266;
        font-size: 14px;
        transition: all 0.3s;

        &:hover {
          color: $primary-color;
        }

        &.active {
          color: $primary-color;
          font-weight: 500;
        }
      }
    }

    .content_login {

      .form_username,
      .form_password {
        margin-bottom: 16px;

        :deep(.el-input__wrapper) {
          height: $input-height;
          border-radius: 4px;
        }
      }

      .btn {
        width: 100%;
        margin-top: 24px;
        margin-bottom: 16px;

        button {
          width: 100%;
          height: $input-height;
          font-size: 16px;
        }
      }

      .forget {
        // background-color: #409eff;
        padding-top: 16px;
        text-align: center;
        font-size: 14px;
        color: #606266;
        display: flex;
        justify-content: center;
        gap: 8px;
        border-top: 1px solid rgba(0, 0, 0, 0.1); // 新增小横线

        span {
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            color: $primary-color;
          }

          &:last-child {
            color: $primary-color;
            font-weight: 500;
          }
        }
      }
    }
  }
}

.form_phone {
  margin-bottom: 16px;

  :deep(.el-input-group__prepend) {
    background-color: #fff;
    border-right: none;
    padding: 0 12px;

    .area-code {
      color: #606266;
      font-size: 14px;
    }
  }

  :deep(.el-input__wrapper) {
    height: $input-height;
    border-radius: 4px;
  }
}

.form_code {
  margin-bottom: 16px;

  :deep(.el-input-group__append) {
    background-color: #fff;
    padding: 0 12px;
    border-left: none;

    .get-code-text {
      color: $primary-color;
      cursor: pointer;
      font-size: 14px;
      white-space: nowrap;
      transition: opacity 0.3s;

      &:hover {
        opacity: 0.8;
      }

      &.disabled {
        color: #c0c4cc;
        cursor: not-allowed;
      }
    }
  }

  :deep(.el-input__wrapper) {
    height: $input-height;
    border-radius: 4px;
    border-right: none;
  }
}
</style>